<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
       <el-form-item label="设备类型" prop="machineType">
        <el-select v-model="formData.machineType" placeholder="请选择设备类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MACHINE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="串口" prop="serialPort">
        <el-select v-model="formData.serialPort" placeholder="请选择串口">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SERIAL_PORT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="波特率" prop="baudRate">
        <el-select v-model="formData.baudRate" placeholder="请选择波特率">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BAUD_RATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据位" prop="dataBits">
        <el-select v-model="formData.dataBits" placeholder="请选择数据位">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DATA_BITS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="停止位" prop="stopBits">
        <el-select v-model="formData.stopBits" placeholder="请选择停止位">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.STOP_BITS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="校验位" prop="parity">
        <el-select v-model="formData.parity" placeholder="请选择校验位">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PARITY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送命令" prop="sendCommand">
        <el-input v-model="formData.sendCommand" placeholder="请输入发送命令" />
      </el-form-item>
      <el-form-item label="接收命令" prop="receiveCommand">
        <el-input v-model="formData.receiveCommand" placeholder="请输入接收命令" />
      </el-form-item>
      <el-form-item label="设备连接类型" prop="connectionType">
        <el-select v-model="formData.connectionType" placeholder="请选择设备连接类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CONNECTION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="本机端口" prop="localPort">
        <el-input v-model="formData.localPort" placeholder="请输入本机端口" />
      </el-form-item>
      <el-form-item label="TPCIP" prop="tcpIp">
        <el-input v-model="formData.tcpIp" placeholder="请输入TPCIP" />
      </el-form-item>
      <el-form-item label="目标端口" prop="targetPort">
        <el-input v-model="formData.targetPort" placeholder="请输入目标端口" />
      </el-form-item>
      <el-form-item label="登录账号" prop="loginAccount">
        <el-input v-model="formData.loginAccount" placeholder="请输入登录账号" />
      </el-form-item>
      <el-form-item label="登录密码" prop="loginPassword">
        <el-input v-model="formData.loginPassword" placeholder="请输入登录密码" />
      </el-form-item>
      <el-form-item label="数据通道" prop="dataChannel">
        <el-input v-model="formData.dataChannel" placeholder="请输入数据通道" />
      </el-form-item>
      <el-form-item label="数据保存路径" prop="dataSavePath">
        <el-input v-model="formData.dataSavePath" placeholder="请输入数据保存路径" />
      </el-form-item>
      <el-form-item label="码流类型" prop="streamType">
        <el-select v-model="formData.streamType" placeholder="请选择码流类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.STREAM_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用 (0-否, 1-是)" prop="enabled">
        <el-radio-group v-model="formData.enabled">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="数据长度" prop="dataLength">
        <el-input v-model="formData.dataLength" placeholder="请输入数据长度" />
      </el-form-item>
      <el-form-item label="初始状态数据" prop="initialStateData">
        <el-input v-model="formData.initialStateData" placeholder="请输入初始状态数据" />
      </el-form-item>
      <el-form-item label="数据开始索引" prop="dataStartIndex">
        <el-input v-model="formData.dataStartIndex" placeholder="请输入数据开始索引" />
      </el-form-item>
      <el-form-item label="数据结束索引" prop="dataEndIndex">
        <el-input v-model="formData.dataEndIndex" placeholder="请输入数据结束索引" />
      </el-form-item>
      <el-form-item label="数据结束标识字符" prop="dataEndMarker">
        <el-input v-model="formData.dataEndMarker" placeholder="请输入数据结束标识字符" />
      </el-form-item>
      <el-form-item label="最小数量" prop="minQuantity">
        <el-input v-model="formData.minQuantity" placeholder="请输入最小数量" />
      </el-form-item>
      <el-form-item label="稳定时间" prop="stableTime">
        <el-date-picker
          v-model="formData.stableTime"
          type="date"
          value-format="x"
          placeholder="选择稳定时间"
        />
      </el-form-item>
      <el-form-item label="是否逆序 (0-否, 1-是)" prop="reverseOrder">
        <el-radio-group v-model="formData.reverseOrder">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="数据结果处理" prop="dataResultProcessing">
        <el-input v-model="formData.dataResultProcessing" placeholder="请输入数据结果处理" />
      </el-form-item>
      <el-form-item label="读取数据间隔" prop="readInterval">
        <el-input v-model="formData.readInterval" placeholder="请输入读取数据间隔" />
      </el-form-item>
      <el-form-item label="编号" prop="number">
        <el-input v-model="formData.number" placeholder="请输入编号" />
      </el-form-item>
      <el-form-item label="对接协议方案" prop="protocolScheme">
        <el-select v-model="formData.protocolScheme" placeholder="请选择对接协议方案">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PROTOCOL_SCHEME)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送目录" prop="sendDirectory">
        <el-input v-model="formData.sendDirectory" placeholder="请输入发送目录" />
      </el-form-item>
      <el-form-item label="工序ID" prop="processId">
        <el-input v-model="formData.processId" placeholder="请输入工序ID" />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input v-model="formData.processName" placeholder="请输入工序名称" />
      </el-form-item>
      <el-form-item label="站号" prop="stationNumber">
        <el-input v-model="formData.stationNumber" placeholder="请输入站号" />
      </el-form-item>
      <el-form-item label="地址是否从0开始 (0-否, 1-是)" prop="addressStartFromZero">
        <el-radio-group v-model="formData.addressStartFromZero">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="数据解析格式" prop="dataParseFormat">
        <el-select v-model="formData.dataParseFormat" placeholder="请选择数据解析格式">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DATA_PARSE_FORMAT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="连接服务器" prop="serverConnection">
        <el-input v-model="formData.serverConnection" placeholder="请输入连接服务器" />
      </el-form-item>
      <el-form-item label="数据库名称" prop="databaseName">
        <el-input v-model="formData.databaseName" placeholder="请输入数据库名称" />
      </el-form-item>
      <el-form-item label="数据库账号" prop="databaseAccount">
        <el-input v-model="formData.databaseAccount" placeholder="请输入数据库账号" />
      </el-form-item>
      <el-form-item label="数据库密码" prop="databasePassword">
        <el-input v-model="formData.databasePassword" placeholder="请输入数据库密码" />
      </el-form-item>
      <el-form-item label="创建ERP单据 (0-否, 1-是)" prop="createErpDocument">
        <el-radio-group v-model="formData.createErpDocument">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="系列" prop="series">
        <el-input v-model="formData.series" placeholder="请输入系列" />
      </el-form-item>
      <el-form-item label="LocalTSAP" prop="localTsap">
        <el-input v-model="formData.localTsap" placeholder="请输入LocalTSAP" />
      </el-form-item>
      <el-form-item label="DestTSAP" prop="destTsap">
        <el-input v-model="formData.destTsap" placeholder="请输入DestTSAP" />
      </el-form-item>
      <el-form-item label="发送URL" prop="sendUrl">
        <el-input v-model="formData.sendUrl" placeholder="请输入发送URL" />
      </el-form-item>
      <el-form-item label="操作间隔" prop="operationInterval">
        <el-input v-model="formData.operationInterval" placeholder="请输入操作间隔" />
      </el-form-item>
      <el-form-item label="是否启用站号信息 (0-否, 1-是)" prop="enableStationInfo">
        <el-radio-group v-model="formData.enableStationInfo">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { BaseMachineApi } from '@/api/erp/basemachine'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  machineId: undefined,
  machineType: undefined,
  serialPort: undefined,
  baudRate: undefined,
  dataBits: undefined,
  stopBits: undefined,
  parity: undefined,
  sendCommand: undefined,
  receiveCommand: undefined,
  connectionType: undefined,
  localPort: undefined,
  tcpIp: undefined,
  targetPort: undefined,
  loginAccount: undefined,
  loginPassword: undefined,
  dataChannel: undefined,
  dataSavePath: undefined,
  streamType: undefined,
  enabled: undefined,
  dataLength: undefined,
  initialStateData: undefined,
  dataStartIndex: undefined,
  dataEndIndex: undefined,
  dataEndMarker: undefined,
  minQuantity: undefined,
  stableTime: undefined,
  reverseOrder: undefined,
  dataResultProcessing: undefined,
  readInterval: undefined,
  number: undefined,
  protocolScheme: undefined,
  sendDirectory: undefined,
  processId: undefined,
  processName: undefined,
  stationNumber: undefined,
  addressStartFromZero: undefined,
  dataParseFormat: undefined,
  serverConnection: undefined,
  databaseName: undefined,
  databaseAccount: undefined,
  databasePassword: undefined,
  createErpDocument: undefined,
  series: undefined,
  localTsap: undefined,
  destTsap: undefined,
  sendUrl: undefined,
  operationInterval: undefined,
  enableStationInfo: undefined
})
const formRules = reactive({
  machineId: [{ required: true, message: '机台id不能为空', trigger: 'blur' }],
  enabled: [{ required: true, message: '是否启用 (0-否, 1-是)不能为空', trigger: 'blur' }],
  reverseOrder: [{ required: true, message: '是否逆序 (0-否, 1-是)不能为空', trigger: 'blur' }],
  addressStartFromZero: [{ required: true, message: '地址是否从0开始 (0-否, 1-是)不能为空', trigger: 'blur' }],
  createErpDocument: [{ required: true, message: '创建ERP单据 (0-否, 1-是)不能为空', trigger: 'blur' }],
  enableStationInfo: [{ required: true, message: '是否启用站号信息 (0-否, 1-是)不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, machineId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.machineId = machineId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BaseMachineApi.getBaseMachineParameter(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await BaseMachineApi.createBaseMachineParameter(data)
      message.success(t('common.createSuccess'))
    } else {
      await BaseMachineApi.updateBaseMachineParameter(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    machineId: undefined,
    machineType: undefined,
    serialPort: undefined,
    baudRate: undefined,
    dataBits: undefined,
    stopBits: undefined,
    parity: undefined,
    sendCommand: undefined,
    receiveCommand: undefined,
    connectionType: undefined,
    localPort: undefined,
    tcpIp: undefined,
    targetPort: undefined,
    loginAccount: undefined,
    loginPassword: undefined,
    dataChannel: undefined,
    dataSavePath: undefined,
    streamType: undefined,
    enabled: undefined,
    dataLength: undefined,
    initialStateData: undefined,
    dataStartIndex: undefined,
    dataEndIndex: undefined,
    dataEndMarker: undefined,
    minQuantity: undefined,
    stableTime: undefined,
    reverseOrder: undefined,
    dataResultProcessing: undefined,
    readInterval: undefined,
    number: undefined,
    protocolScheme: undefined,
    sendDirectory: undefined,
    processId: undefined,
    processName: undefined,
    stationNumber: undefined,
    addressStartFromZero: undefined,
    dataParseFormat: undefined,
    serverConnection: undefined,
    databaseName: undefined,
    databaseAccount: undefined,
    databasePassword: undefined,
    createErpDocument: undefined,
    series: undefined,
    localTsap: undefined,
    destTsap: undefined,
    sendUrl: undefined,
    operationInterval: undefined,
    enableStationInfo: undefined
  }
  formRef.value?.resetFields()
}
</script>